package cn.flant.ssl;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import cn.flant.file.FileUtil;
import cn.flant.io.IOUtil;

public class SSLHelper {

	public static KeyStore initKeyStore(String keyFile, char[] password) throws Exception {
		KeyStore ks = KeyStore.getInstance("jks");
		InputStream input = FileUtil.loadFile(keyFile);
		if (input == null) {
			throw new FileNotFoundException(keyFile);
		}
		try {
			ks.load(input, password);
		} finally {
			IOUtil.close(input);
		}
		return ks;
	}

	public static SSLContext initSSLContext(String keyFile, char[] password) throws Exception {
		KeyStore ks = initKeyStore(keyFile, password);
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, password);
		SSLContext ctx = SSLContext.getInstance("SSLv3");
		ctx.init(kmf.getKeyManagers(), null, null);
		return ctx;
	}

	public static SSLContext initSSLContext(String keyFile) throws Exception {
		KeyStore ks = initKeyStore(keyFile, null);
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(ks);
		SSLContext ctx = SSLContext.getInstance("SSLv3");
		ctx.init(null, tmf.getTrustManagers(), null);
		return ctx;
	}
}
